import EditModal from "@/pages/Admin/Resource/Article/components/EditModal";
import {articleDeleteReq, articleListReq, articleSaveReq, articleSaveTagReq, tagListReq} from "@/service/resource.ts";
import {SuccessCode} from "@/utils/request.ts";
import {Button, Form, InputRef, message, Modal, Popconfirm, Select, Space, Table, Tag, Typography} from "antd";
import {useForm} from "antd/es/form/Form";
import FormItem from "antd/es/form/FormItem";
import Input from "antd/es/input/Input";
import {ColumnsType} from "antd/es/table";
import {useEffect, useRef, useState} from "react";
import {useTranslation} from "react-i18next";
import CustomSelect from "./components/CustomSelect";
import styles from './index.module.less';

const articleStatusMap = new Map([
    [1, "编辑中"],
    [2, "已上线"],
    [3, "已下架"],
    [4, "已删除"],
]);

const ArticleManage = () => {
    const [t] = useTranslation()
    const createFormInput = useRef<InputRef>(null)
    const [searchForm] = useForm()
    const [createForm] = useForm()
    const [isShowCreateModal, setIsShowCreateModal] = useState(false)
    const [isShowEditModal, setIsShowEditModal] = useState(false)
    const [tagList, setTagList] = useState<API.TagListRespItem[]>([])
    const [tableLoading, setTableLoading] = useState(false)
    const [tableData, setTableData,] = useState<API.ArticleListRespItem[]>([])
    const [operationArticle, setOperationArticle] = useState<API.ArticleListRespItem>()

    function onDeleteTag(record: API.ArticleListRespItem, item: API.ArticleListRespItemTag) {
        return () => {
            articleSaveTagReq({
                article_id: record.id,
                tag_names: record.tags.filter(tag => tag.id != item.id).map(item => item.name)
            }).then(res => {
                if (res.code == SuccessCode) {
                    message.success("操作成功")
                    loadTableData()
                }
            })
        };
    }


    useEffect(() => {
        loadTableData()
        loadTagList()
    }, [])

    const loadTagList = () => {
        tagListReq({}).then(res => {
            if (res.code == SuccessCode) {
                setTagList(res.data.items)
            }
        })
    }

    const loadTableData = () => {
        setTableLoading(true)
        articleListReq({...searchForm.getFieldsValue()}).then(res => {
            if (res.code === SuccessCode) {
                setTableData(res.data.items)
            }
        }).finally(() => {
            setTableLoading(false)
        })
    }

    const onSaveTag = () => {
        articleSaveTagReq({
            article_id: operationArticle?.id,
            tag_names: [...new Set(operationArticle?.tags.map(item => item.name))]
        }).then(res => {
            if (res.code == SuccessCode) {
                message.success(t("page.operation.success"))
                loadTableData()
                loadTagList()
            } else {
                message.error(t("page.operation.error"))

            }
        }).finally(() => {
        })
    }

    const onCreate = () => {
        articleSaveReq({...createForm.getFieldsValue()}).then(res => {
            if (res.code === SuccessCode) {
                loadTableData()
                setOperationArticle(res.data as never as API.ArticleListRespItem)
                setIsShowEditModal(true)
                setIsShowCreateModal(false)
                createForm.resetFields()
                message.success(t("page.operation.success"))
            } else {
                message.success(`${t("page.operation.error")}: ${res.msg}`)
            }
        })
    }

    const onEdit = (record: API.ArticleListRespItem) => {
        setOperationArticle(record)
        setIsShowEditModal(true)

    }

    const onDelete = (id: string) => {
        articleDeleteReq({id: id}).then(res => {
            if (res.code === SuccessCode) {
                loadTableData()
                message.success(t("page.operation.success"))
            } else {
                message.success(`${t("page.operation.error")}: ${res.msg}`)
            }
        })
    }

    const renderSearchForm = () => {
        return (
            <Form form={searchForm} layout={'inline'}>
                <FormItem label={t("page.article.name")} name={"name"}>
                    <Input placeholder={t("page.pleaseInput")}/>
                </FormItem>
                <FormItem label={t("page.article.tag")} name={'tag_names'}>
                    <Select placeholder={t("page.pleaseSelect")} mode={"multiple"} style={{minWidth: 120}}
                            options={tagList.map(item => {
                                return {label: item.name, value: item.name}
                            })}/>
                </FormItem>
                <FormItem>
                    <Button type={"primary"} onClick={loadTableData}>{t("page.search")}</Button>
                </FormItem>
                <FormItem>
                    <Button type={"dashed"} onClick={() => {
                        searchForm.resetFields()
                        loadTableData()
                    }}>{t("page.reset")}</Button>
                </FormItem>
            </Form>
        )
    }

    const renderCreateModal = () => {
        return (
            <Modal open={isShowCreateModal}
                   title={t("page.article.createArticle")}
                   onCancel={() => setIsShowCreateModal(false)}
                   onOk={() => createForm.submit()}
                   afterOpenChange={(v) => {
                       if (v) {
                           createFormInput.current?.focus()
                       }
                   }}
            >
                <Form form={createForm} style={{padding: "20px 40px"}} onFinish={onCreate} autoComplete="off"
                >
                    <FormItem label={t("page.article.name")} name={"name"} rules={[{
                        required: true,
                        message: t("page.form.required.input", {value: t("page.article.name")})
                    }]}>
                        <Input ref={createFormInput} placeholder={t("page.pleaseInput")}/>
                    </FormItem>
                </Form>
            </Modal>
        )
    }

    const renderEditModal = () => {
        return (
            <Modal open={isShowEditModal}
                   width={"100%"}
                   wrapClassName="full-modal"
                   closable={false}
                   footer={null}
            >
                <EditModal
                    article={operationArticle}
                    onClose={() => {
                        setIsShowEditModal(false)
                        loadTableData()
                    }}/>
            </Modal>
        )
    }


    const tableColumns: ColumnsType<API.ArticleListRespItem> = [
        {
            title: "ID",
            dataIndex: "id",
            width: 200,
            render: value =>
                <Typography.Text style={{width: 100}}
                                 ellipsis={{tooltip: value}}>
                    {value}
                </Typography.Text>
        },
        {
            title: t('page.article.name'),
            dataIndex: "name"
        },
        {
            title: t('page.article.tag'),
            dataIndex: "tags",
            render: (value: API.ArticleListRespItemTag[], record) =>
                <Space >
                    {value.map(item =>
                        <Popconfirm key={item.id} showCancel={false} okText={"Yes"} onConfirm={onDeleteTag(record, item)}
                                    title={"是否删除？"}>
                            <Tag className={"cursor-pointer"}>{item.name}</Tag>
                        </Popconfirm>
                    )}
                    <Popconfirm
                        placement="bottom"
                        title={null}
                        description={
                            <div style={{margin: 20}}>
                                <CustomSelect options={tagList.map(item => {
                                    return {label: item.name, value: item.name}
                                })} mode={"multiple"} onSelect={(v) => {
                                    if (operationArticle) {
                                        setOperationArticle({
                                            ...operationArticle, tags: [...value, ...v.map(name => ({
                                                name
                                            } as API.ArticleListRespItemTag))]
                                        })
                                    }
                                }}/>
                            </div>
                        }
                        onOpenChange={() => {
                            setOperationArticle(record)
                        }}
                        onConfirm={onSaveTag}
                        showCancel={false}
                        icon={null}
                        okText={null}
                    >
                        <Tag style={{cursor: "pointer"}}>添加</Tag>
                    </Popconfirm>
                </Space>
        },
        {
            title: t('page.article.status'),
            dataIndex: "status",
            render: (value: number) => <Tag>{articleStatusMap.get(value)}</Tag>
        },
        {
            title: t('page.action'),
            width: 120,
            render: (_, record) => {
                return (
                    <Space>
                        <Popconfirm title={t('page.delete.prompt', {value: t("page.article")})}
                                    onConfirm={() => onDelete(record.id)}>
                            <Button type={"link"} danger>{t("page.delete")}</Button>
                        </Popconfirm>

                        <Button type={"link"} onClick={() => onEdit(record)}>{t("page.edit")}</Button>
                    </Space>
                )
            }
        }
    ]

    return (
        <div className={styles.ArticleManage}>
            {renderSearchForm()}
            <div className={styles.ActionWrap}>
                <Space>
                    <Button type={"primary"} onClick={() => {
                        setIsShowCreateModal(true)
                    }}>{t("page.create")}</Button>
                </Space>
            </div>
            <Table style={{marginTop: 20}} loading={tableLoading} columns={tableColumns} dataSource={tableData}
                   rowKey={"id"}/>
            {renderCreateModal()}
            {renderEditModal()}
        </div>
    );
};

export default ArticleManage;
